<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="计划编号" prop="planId">
              <el-input v-model="queryParams.planId" placeholder="请输入计划编号" clearable />
            </el-form-item>
            <el-form-item label="发货时间" prop="deliveryTime">
              <el-date-picker v-model="queryParams.deliveryTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择发货时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['delivery:deliveryPlanFinal:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['delivery:deliveryPlanFinal:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['delivery:deliveryPlanFinal:remove']"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['delivery:deliveryPlanFinal:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <div>
        <section class="my-gantt">
          <div id="gantt_here" class="gantt-container"></div>
        </section>
      </div>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改最终发货计划对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="deliveryPlanFinalFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划编号" prop="planId">
          <el-input v-model="form.planId" placeholder="请输入计划编号" />
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker v-model="form.deliveryTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物流商id(补货方式)" prop="ryLogisticsId">
          <el-input v-model="form.ryLogisticsId" placeholder="请输入物流商id(补货方式)" />
        </el-form-item>
        <el-form-item label="物流商名称" prop="ryLogisticName">
          <el-input v-model="form.ryLogisticName" placeholder="请输入物流商名称" />
        </el-form-item>
        <el-form-item label="物流渠道ID" prop="logisticsinfoId">
          <el-input v-model="form.logisticsinfoId" placeholder="请输入物流渠道ID" />
        </el-form-item>
        <el-form-item label="物流渠道名称" prop="logisticsinfoName">
          <el-input v-model="form.logisticsinfoName" placeholder="请输入物流渠道名称" />
        </el-form-item>
        <el-form-item label="目的国家" prop="targetAddress">
          <el-input v-model="form.targetAddress" placeholder="请输入目的国家" />
        </el-form-item>
        <el-form-item label="提货地" prop="pickupAddress">
          <el-input v-model="form.pickupAddress" placeholder="请输入提货地" />
        </el-form-item>
        <el-form-item label="运输方式" prop="transportMethod">
          <el-input v-model="form.transportMethod" placeholder="请输入运输方式" />
        </el-form-item>
        <el-form-item label="预计时效天数" prop="expectedDeliveryTimeDays">
          <el-input v-model="form.expectedDeliveryTimeDays" placeholder="请输入预计时效天数" />
        </el-form-item>
        <el-form-item label="预计到货时间" prop="expectedDeliveryTime">
          <el-date-picker
            v-model="form.expectedDeliveryTime"
            clearable
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预计到货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总发货数量" prop="totalQuantity">
          <el-input v-model="form.totalQuantity" placeholder="请输入总发货数量" />
        </el-form-item>
        <el-form-item label="货件编号" prop="fbaNo">
          <el-input v-model="form.fbaNo" placeholder="请输入货件编号" />
        </el-form-item>
        <el-form-item label="实际时效天数" prop="actualDeliveryTimeDays">
          <el-input v-model="form.actualDeliveryTimeDays" placeholder="请输入实际时效天数" />
        </el-form-item>
        <el-form-item label="实际到货时间" prop="actualDeliveryTime">
          <el-date-picker
            v-model="form.actualDeliveryTime"
            clearable
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择实际到货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="亚马逊后台当前已接收总数量" prop="currentReceivedTotalQuantity">
          <el-input v-model="form.currentReceivedTotalQuantity" placeholder="请输入亚马逊后台当前已接收总数量" />
        </el-form-item>
        <el-form-item label="总重量" prop="totalWeight">
          <el-input v-model="form.totalWeight" placeholder="请输入总重量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalMoney">
          <el-input v-model="form.totalMoney" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="部门id" prop="handlerDeptId">
          <el-input v-model="form.handlerDeptId" placeholder="请输入部门id" />
        </el-form-item>
        <el-form-item label="用户id" prop="handlerUserId">
          <el-input v-model="form.handlerUserId" placeholder="请输入用户id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeliveryPlanFinal" lang="ts">
import {
  listDeliveryPlanFinal,
  getDeliveryPlanFinal,
  delDeliveryPlanFinal,
  addDeliveryPlanFinal,
  updateDeliveryPlanFinal
} from '@/api/delivery/deliveryPlanFinal';
import { DeliveryPlanFinalVO, DeliveryPlanFinalForm, DeliveryPlanGanttDto, DeliveryPlanFinalQuery } from '@/api/delivery/deliveryPlanFinal/types';

import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ganttDtoList = ref<DeliveryPlanGanttDto[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const deliveryPlanFinalFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeliveryPlanFinalForm = {
  id: undefined,
  planId: undefined,
  deliveryTime: undefined,
  ryLogisticsId: undefined,
  ryLogisticName: undefined,
  logisticsinfoId: undefined,
  logisticsinfoName: undefined,
  targetAddress: undefined,
  pickupAddress: undefined,
  transportMethod: undefined,
  expectedDeliveryTimeDays: undefined,
  expectedDeliveryTime: undefined,
  deliveryPlanStatus: undefined,
  totalQuantity: undefined,
  fbaNo: undefined,
  actualDeliveryTimeDays: undefined,
  actualDeliveryTime: undefined,
  currentReceivedTotalQuantity: undefined,
  totalWeight: undefined,
  unitPrice: undefined,
  totalMoney: undefined,
  paymentStatus: undefined,
  remark: undefined,
  handlerDeptId: undefined,
  handlerUserId: undefined
};
const data = reactive<PageData<DeliveryPlanFinalForm, DeliveryPlanFinalQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planId: undefined,
    deliveryTime: undefined,
    // ryLogisticsId: undefined,
    // ryLogisticName: undefined,
    // logisticsinfoId: undefined,
    // logisticsinfoName: undefined,
    // targetAddress: undefined,
    // pickupAddress: undefined,
    // transportMethod: undefined,
    // expectedDeliveryTimeDays: undefined,
    // expectedDeliveryTime: undefined,
    // deliveryPlanStatus: undefined,
    // totalQuantity: undefined,
    // fbaNo: undefined,
    // actualDeliveryTimeDays: undefined,
    // actualDeliveryTime: undefined,
    // currentReceivedTotalQuantity: undefined,
    // totalWeight: undefined,
    // unitPrice: undefined,
    // totalMoney: undefined,
    // paymentStatus: undefined,
    // handlerDeptId: undefined,
    // handlerUserId: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deliveryPlanFinalFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeliveryPlanFinalVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加最终发货计划';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeliveryPlanFinalVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeliveryPlanFinal(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改最终发货计划';
};

/** 提交按钮 */
const submitForm = () => {
  deliveryPlanFinalFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDeliveryPlanFinal(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDeliveryPlanFinal(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeliveryPlanFinalVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除最终发货计划编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDeliveryPlanFinal(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'delivery/deliveryPlanFinal/export',
    {
      ...queryParams.value
    },
    `deliveryPlanFinal_${new Date().getTime()}.xlsx`
  );
};

//初始化甘特图
const initGantt = () => {
  // 是否显示左侧表格(默认是开启)
  gantt.config.show_grid = true;

  gantt.config.grid_width = 350;
  gantt.config.add_column = false; //添加符号
  //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
  gantt.config.autofit = false;
  // 设置行的高度
  gantt.config.row_height = 60;
  // 设置bar的高度
  gantt.config.bar_height = 45;
  gantt.config.fit_tasks = true; //自动延长时间刻度，以适应所有显示的任务
  gantt.config.auto_types = true; //将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
  // 甘特图时间格式 和 自己的数据格式一致
  // gantt.config.xml_date = '%Y-%m-%d'

  gantt.i18n.setLocale('cn'); //设置语言

  // gantt.config.scale_unit = "month"; //时间轴单位
  gantt.config.step = 2; //单位数
  // gantt.config.date_scale = "%Y年%M";//时间轴展现方式
  gantt.config.date_format = '%Y-%m-%d';
  // 表格列设置 text start_date 都是返回的字符串里面的 字段
  gantt.config.columns = [
    { name: 'asin', label: 'ASIN', width: '120', align: 'center' },
    { name: 'ryLogisticName', label: '物流公司', width: '100', align: 'center' },
    { name: 'logisticsinfoName', label: '物流渠道', width: '100', align: 'center' },
    { name: 'fbaSellableQuantity', label: 'FBA可售/补货数量', width: '100', align: 'center' },
    { name: 'everyDaySale', label: '每日销量', width: '100', align: 'center' },
    { name: 'start_date', label: '可售开始时间', width: '100', align: 'center' },
    { name: 'sellableEndTime', label: '可售截止时间', width: '100', align: 'center' }
  ];
  // 表头刻度线
  // gantt.config.scales = [{ unit: 'month', step: 1, date: ' %Y 年  %F' }, { unit: 'day', step: 1, date: '%d' }];
  // 表头的高度
  gantt.config.scale_height = 100;
  // 格式化时间
  // gantt.locale.date = {
  //     month_full: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  //     month_short: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  //     day_full: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  //     day_short: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  // };
  // 尽量不出现滚动条展示全部
  // gantt.config.autosize = false;

  // false的时候 可编辑
  gantt.config.readonly = false; //是否只读
  // 允许拖放(靠这个去 修改发货计划)
  gantt.config.drag_project = true;
  // 设置进度条上显示的文字
  gantt.templates.progress_text = function (start, end, task) {
    return "<span style='text-align:left;'>" + task.fbaSellableQuantity + '% </span>';
  };

  gantt.templates.task_text = function (start, end, task) {
    return "<span style='text-align:left;'>" + task.fbaSellableQuantity + '</span>';
  };

  gantt.init('gantt_here');
};

const newMapData = () => {
  const mapData = {
    id: undefined,
    asin: undefined,
    ryLogisticName: undefined,
    logisticsinfoName: undefined,
    fbaSellableQuantity: undefined,
    everyDaySale: undefined,
    start_date: undefined,
    duration: undefined,
    parent: undefined,
    sellableEndTime: undefined,
    open: undefined
  };
  return mapData;
};

/** 查询最终发货计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeliveryPlanFinal(queryParams.value);

  total.value = res.total;

  ganttDtoList.value = res.rows;

  // 清除原来的数据
  gantt.clearAll();

  let ganttData1 = {
    data: []
  };

  ganttData1.data = ganttDtoList.value.map((item) => {
    let mp = newMapData();
    mp.id = item.id;
    mp.asin = item.asin;
    mp.ryLogisticName = item.ryLogisticName;
    mp.logisticsinfoName = item.logisticsinfoName;
    mp.fbaSellableQuantity = item.fbaSellableQuantity;
    mp.everyDaySale = item.everyDaySale;
    mp.start_date = item.startDate;
    mp.duration = item.duration;
    mp.parent = item.parent;
    mp.sellableEndTime = item.sellableEndTime;
    mp.open = true;
    return mp;
  });

  // let ganttData = {
  //   tasks: JSON.stringify(res.rows)
  // }

  console.log(ganttData1.data);

  gantt.parse(ganttData1);

  // 只需要在这里 ganttDataArr 设置这个值,就可以渲染对应的数据
  // 再给 修改 和 拖拽绑定时间,就可以做到 可视化修改发货计划
  loading.value = false;
};

onMounted(() => {
  initGantt();
  getList();
});
</script>

<style scoped lang="scss">
.my-gantt {
  height: 800px;
  width: 100vw;

  .gantt-container {
    width: 85%;
    height: 100%;
    overflow: auto;
  }
}
</style>
